#include <iostream>
#include <thread>
#include "read_config.hpp"
#include "capture.hpp"

static std::string get_curr_time()
{
	time_t rawtime;
	time(&rawtime);
	struct tm *timeinfo = localtime(&rawtime);
	std::stringstream ss;
	ss << timeinfo->tm_year + 1900 << "_" << timeinfo->tm_mon + 1
		<< "_" << timeinfo->tm_mday << "_" << timeinfo->tm_hour
		<< "_" << timeinfo->tm_min;
	std::string res;
	ss >> res;
	return res;
}

int main()
{
	std::string str_config_file_path("F:\\temp\\videoRecord.json");
	SVideoRecordParam video_record_param;
	memset(&video_record_param, 0, sizeof(SVideoRecordParam));
	if (!read_video_record_param(str_config_file_path, video_record_param)) {
		std::cerr << "read config file failed." << std::endl;
		return 1;
	}
	std::cout << "video stream path: ";
	std::cout << video_record_param.str_video_stream_path_ << std::endl;
	std::cout << "video save folder: ";
	std::cout << video_record_param.str_save_folder_ << std::endl;
	std::cout << "video save minutes: ";
	std::cout << video_record_param.video_save_minutes_ << std::endl;

	gentech::SCaptureParam capture_param;
	memset(&capture_param, 0, sizeof(gentech::SCaptureParam));
	capture_param.str_video_path_ = video_record_param.str_video_stream_path_;
	gentech::CCapture capture;
	if (!capture.init(capture_param)) {
		std::cerr << "capture init failed." << std::endl;
		return 1;
	}

	std::string str_curr_time = get_curr_time();
	std::string str_video_save_path = 
		video_record_param.str_save_folder_ + "\\" + str_curr_time + ".avi";
	cv::VideoWriter video_writer;

	int nsave_counts = video_record_param.video_save_minutes_ * 60 * 25;
	int ncount = 1;
	cv::Mat frame;
	cv::namedWindow("show", 0);
	while (ncount <= nsave_counts) {
		if (!capture.capture(frame)) break;
		if (frame.empty()) {
			std::this_thread::sleep_for(std::chrono::milliseconds(1));
			continue;
		}
		if (!video_writer.isOpened()) {
			video_writer.open(str_video_save_path, CV_FOURCC('X', 'V', 'I', 'D'), 25,
				frame.size(), true);
			if (!video_writer.isOpened()) {
				std::cerr << "can not create the save video." << std::endl;
				break;
			}
		}
		cv::imshow("show", frame);
		video_writer << frame;
		if (cv::waitKey(1) == 27) break;
		++ncount;
	}
	cv::destroyAllWindows();

	return 0;
}